const grpc = require('@grpc/grpc-js')
const message_proto = require('./proto')
const const_module = require('./Global')
const { v4: uuidv4 } = require('uuid');
const emailModule = require('./email');
const redis_module = require('./redis');


/**
 * GetVarifyCode grpc响应获取验证码的服务
 * @param {*} call 为grpc请求 
 * @param {*} callback 为grpc回调
 * @returns 
 */

async function GetVarifyCode(call, callback) {
    console.log("email is :",call.request.email)
    try {
        let query_res = await redis_module.GetRedis(const_module.code_prefix+call.request.email);
        let uniqueId = query_res;
        if(query_res == null){

            // 删除可能的空值键
            let del_res = await redis_module.DeleteRedis(const_module.code_prefix+call.request.email);
            uniqueId = uuidv4().substring(0,5);
            const set_res = await redis_module.SetNxRedisExpire(const_module.code_prefix+call.request.email, uniqueId.toUpperCase(),180);
            if(!set_res){
                callback(null, { 
                    email:  call.request.email,
                    message: "验证码已存在，请勿重复请求！",
                    error:const_module.Errors.RedisErr
                });
                return;
            }
        }

        let text_str = '您的验证码为'+ uniqueId.toUpperCase() + ',请在三分钟内完成注册！';

        // 发送邮件
        let mailOptions = {
            from: 'q53899031@163.com',
            to: call.request.email,
            subject: '验证码',
            text: text_str
        };

        const send_res = await emailModule.SendMail(mailOptions)
        console.log("send_res.code is :",send_res.code)
        if (!send_res) {
            // 邮件发送失败，清理 Redis
            await redis_module.DeleteRedis(const_module.code_prefix+call.request.email);
            throw new Error('邮件发送失败');
        }

        console.log("send_res is :",send_res)
        callback(null, {     
            email:  call.request.email,       
            error_message: "验证码已发送至邮箱，请注意查收！",
            error_code:const_module.error_code.Success,
            verify_code:uniqueId.toUpperCase()
        });
    } catch (error) {
        console.log("error is :",error)
        callback(null, {
            email:  call.request.email,
            message: "验证码发送失败，请检查邮箱地址是否正确！",
            error:const_module.error_code.Exception 
        });
        
    }

}


function main(){
    var server = new grpc.Server();
    server.addService(message_proto.VarifyService.service, {
        GetVarifyCode: GetVarifyCode
    });
    server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(),() => {
        // server.start();
        console.log('Server running at http://0.0.0.0:50051');
        
    });

}

main();

